package com.example.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.config.R;
import com.example.dto.DishDto;
import com.example.entity.Category;
import com.example.entity.Dish;
import com.example.entity.DishFlavor;
import com.example.service.CategoryService;
import com.example.service.DishFlavorService;
import com.example.service.DishService;
import com.example.service.SetmealService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("dish")
@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Resource
    SetmealService setmealService;


//    @GetMapping("/page")
//    public R<Page> page(int page, int pageSize,String name){
//        //log.info("page={},pageSize={},name={}", page, pageSize, name);
//        // 构造分页构造器
//        Page<Dish> pageInfo = new Page(page, pageSize);
//        // 因为前端需要展示分类的名称，所以封装成DishDto对象
//        Page<DishDto> dishDtoPage = new Page(page, pageSize);
//        // 构造条件
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
//        // 添加排序
//        queryWrapper.orderByDesc(Dish::getUpdateTime);
//        // 执行查询
//        dishService.page(pageInfo, queryWrapper);
//        // 进行对象拷贝,去除之前已经查出来的集合
//        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
//
//        List<Dish> records = pageInfo.getRecords();
//        List<DishDto> list = records.stream().map((item)->{
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(item,dishDto);
//            // 获取categoryId
//            Long categoryId = item.getCategoryId();
//            // 给categoryName赋值
//            Category category = categoryService.getById(categoryId);
//            if(category!=null){
//                dishDto.setCategoryName(category.getName());
//            }
//            // 当前菜品ID
//            Long dishId = item.getId();
//            LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper= new LambdaQueryWrapper<>();
//            dishFlavorQueryWrapper.eq(DishFlavor::getDishId,dishId);
//            List<DishFlavor> dishFlavorList = flavorService.list(dishFlavorQueryWrapper);
//            dishDto.setFlavors(dishFlavorList);
//            return dishDto;
//        }).collect(Collectors.toList());
//        dishDtoPage.setRecords(list);
//        return R.success(dishDtoPage);
//    }
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> queryWrapper  = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //添加排序
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,queryWrapper);
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records=pageInfo.getRecords();
        List<DishDto> list=records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId=item.getCategoryId();
            Category category=categoryService.getById(categoryId);
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }
            Long dishId=item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper  = new LambdaQueryWrapper<>();
            dishFlavorQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList=dishFlavorService.list(dishFlavorQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);

    }



    //套餐管理的添加菜品
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getUpdateTime);
        List<Dish> dishList=dishService.list(queryWrapper);
        List<DishDto> dishDtoList=dishList.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //获取categoryid的值
            Long categoryId=item.getCategoryId();
            Category category=categoryService.getById(categoryId);
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }
            //当前菜品ID
            Long dishId=item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList=dishFlavorService.list(dishFlavorQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);

    }





    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody DishDto dishDto){
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setUpdateTime(LocalDateTime.now());
        Long id=(Long) request.getSession().getAttribute("employee");
        dishDto.setCreateUser(id);
        dishDto.setUpdateUser(id);//获取创建者和修改者
        dishService.saveWithFlover(request,dishDto);
        return R.success("成功");
    }


    @GetMapping("/{id}")
    public R findId(@PathVariable Long id){
        if (id==null){
            return R.error("参数异常");
        }
        DishDto dishDto=dishService.findId(id);
        if (dishDto==null){
            return R.error("回显失败");
        }
        return R.success(dishDto);
    }

    @PutMapping
    public R update(@RequestBody DishDto dishDto,HttpServletRequest request){
        Long id=(Long)request.getSession().getAttribute("employee");
        dishDto.setCreateUser(id);
        dishDto.setUpdateUser(id);
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setCreateTime(LocalDateTime.now());
        dishService.updateByDishId(dishDto);
        return R.success("修改成功");
    }

    //菜品的起售与停售
    @PostMapping("/status/{status}")
    public R<String> onOrclose(@PathVariable Integer status,Long[] ids){
        for (int i=0;i<ids.length;i++){
            Dish dish=dishService.getById(ids[i]);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("修改成功");
    }
    @DeleteMapping
    public R deleteIds(@RequestParam List<Long> ids){
        dishService.removeWithDish(ids);
        return R.success("删除成功");
    }

}
